import React, { useState, useEffect, useRef } from 'react';
import EChartsReact from './index';
import { useScreen } from '@/hooks/useScreen';

// 示例数据
const generateData = () => {
  return [
    { name: 'Mon', value: 120 },
    { name: 'Tue', value: 200 },
    { name: 'Wed', value: 150 },
    { name: 'Thu', value: 80 },
    { name: 'Fri', value: 70 },
    { name: 'Sat', value: 110 },
    { name: 'Sun', value: 130 },
  ];
};

const EChartsDemo: React.FC = () => {
  const [data, setData] = useState(generateData());
  const [loading, setLoading] = useState(false);
  const [theme, setTheme] = useState<'light' | 'dark'>('light');
  const useScreenRef = useRef<HTMLDivElement>(null);
  
  // 使用useScreen钩子进行大屏适配
  useScreen(useScreenRef.current);
  // 模拟数据更新
  useEffect(() => {
    const interval = setInterval(() => {
      setData(generateData());
    }, 5000);

    return () => clearInterval(interval);
  }, []);

  // 图表配置项
  const option = {
    title: {
      text: 'ECharts Demo',
      subtext: '数据实时更新',
      left: 'center',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    xAxis: {
      type: 'category',
      data: data.map((item) => item.name),
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        data: data.map((item) => item.value),
        type: 'bar',
        itemStyle: {
          color: '#5470c6',
        },
      },
    ],
  };

  // 事件处理
  const handleChartReady = (chart: any) => {
    console.log('图表已准备就绪');
  };

  const handleChartClick = (params: any) => {
    console.log('图表被点击:', params);
  };

  // 切换主题
  const toggleTheme = () => {
    setTheme((prev) => (prev === 'light' ? 'dark' : 'light'));
  };

  // 模拟加载状态
  const toggleLoading = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 2000);
  };

  return (
    <div style={{ padding: '20px' }} ref={useScreenRef}>
      <h2>ECharts React组件使用示例</h2>

      <div style={{ marginBottom: '20px' }}>
        <button onClick={toggleTheme} style={{ marginRight: '10px' }}>
          切换主题 ({theme})
        </button>
        <button onClick={toggleLoading}>模拟加载</button>
      </div>

      <div style={{ width: '100%', height: '400px' }}>
        <EChartsReact
          option={option}
          theme={theme}
          loading={loading}
          onChartReady={handleChartReady}
          onEvents={{
            click: handleChartClick,
          }}
          style={{ height: '100%' }}
        />
      </div>

      <div style={{ marginTop: '20px' }}>
        <h3>使用说明:</h3>
        <ul>
          <li>图表每5秒自动更新数据</li>
          <li>点击"切换主题"按钮可以在浅色和深色主题间切换</li>
          <li>点击"模拟加载"按钮可以查看加载状态效果</li>
          <li>点击图表柱子可以触发点击事件</li>
        </ul>
      </div>
    </div>
  );
};

export default EChartsDemo;
